$(function () {
    $('.option div span').click(function (e) {
        var t = $(this);
        $(".option ul").hide();
        $(this).next("ul").show().find("a").click(function () {
            var val = $(this).html();
            t.html(val);
        });

        return false;
    });
    $(".ft_opt a").mousedown(function () {
        $(this).addClass("mousedown");
    });
    $(".ft_opt a").mouseup(function () {
        $(this).removeClass("mousedown");
    });
    $(document).click(function () {
        $(".option ul").hide();
    });
    //关闭
    $(".close").click(function () {
        $(this).parents(".dialog").hide();
    });
    $(".close_all").click(function () {
        window.location.href = "index.html";
    });
    $('.lookfor').click(function () {
        $('#ap_list').show();
    })
    //
    $(".ap_list table tr").hover(function () {
        $(this).addClass("bg");
    }, function () {
        $(this).removeClass("bg")
    })
});

var Application = function () {
    this.adapter_list = Array();
    this.access_point_list = Array();

    this.loadAdapterList = function () {
        this.adapter_list = $.parseJSON(Wifi.get_wireless_device());
        $(this.adapter_list).each(function (index, item) {
            $(".adapter").html(String.format("<option value=\"{0}\">{1}</option>", item.name, item.name));
        });
    };
    this.changeState = function(status, ssid, bssid, ipAddr){
        $("#status").html(status);
        $("#ssid").html(ssid);
        $("#bssid").html(bssid);
        $("#ipAddr").html(ipAddr);
    };
    this.refreshStatus = function () {
        $("#cur_adapter").bind("change", $.proxy(function () {
            var index = $("#cur_adapter").get(0).selectedIndex;
            var active_connection = this.adapter_list[index].active_connection;
            this.changeState(active_connection.status, active_connection.ssid,
                active_connection.bssid, active_connection.ipAddr);
        }, this));
    };
    this.loadAccessPoint = function () {
        var adapter = $("#cur_adapter").val();
        this.access_point_list = $.parseJSON(Wifi.get_access_point(adapter));
        $("#access_point_list").html("");
        $(this.access_point_list).each(function (index, item) {
            var a = String.format('<a href="javascript:showConnectionAp(\'{0}\')">连接</a>', item.ssid);
            $("#access_point_list").append(String.format("<tr><td>{0}</td><td>{1}</td><td>{2}%</td>" +
                "<td>{3}</td><td>{4}</td></tr>", item.bssid, item.ssid, item.strength, item.frequency, a));
        });
    };
    this.connectionAp = function (ssid, pwd) {
        var adapter = $("#cur_adapter").val();
        Wifi.connection(adapter, ssid, pwd);
    };
    this.disconnect = function(){
        var adapter = $("#cur_adapter").val();
        Wifi.disconnect(adapter);
    };
    this.getConnection = function(name){
        var json = Wifi.get_connection_by_name(name);
        return $.parseJSON(json);
    };
    this.connectionDeviceState = function(func){
        var adapter = $("#cur_adapter").val();
        WifiSignal.deviceStateSignal.connect(func);
        Wifi.connection_device_state(adapter)
    };
    this.deleteConnection = function(name){
        var adapter = $("#cur_adapter").val();
        Wifi.delete_connection(adapter, name);
    };
//    this.showSoftKeyboard = function(){
//        return Wifi.show_soft_keyboard();
//    };
};

function showConnectionAp(ssid) {
    $("#confi_dlg_msg").html('');
    $("#cur_ssid").val(ssid);
    var setting = app.getConnection(ssid);
    $("#cur_pwd").val("");
    if(setting){
        $("#cur_pwd").val(setting.password);
    }
    $("#config_dlg").show();
}

function networkStateChange(state) {
    /*NM_STATE_UNKNOWN = 0
     Networking state is unknown.
     NM_STATE_ASLEEP = 10
     Networking is inactive and all devices are disabled.
     NM_STATE_DISCONNECTED = 20
     There is no active network connection.
     NM_STATE_DISCONNECTING = 30
     Network connections are being cleaned up.
     NM_STATE_CONNECTING = 40
     A network device is connecting to a network and there is no other available network connection.
     NM_STATE_CONNECTED_LOCAL = 50
     A network device is connected, but there is only link-local connectivity.
     NM_STATE_CONNECTED_SITE = 60
     A network device is connected, but there is only site-local connectivity.
     NM_STATE_CONNECTED_GLOBAL = 70
     A network device is connected, with global network connectivity.*/
    if (state == 20) {
        //断开链接
    }
    if (state == 40) {
        //连接中
    }
    if (state == 70) {
        //已连接
    }
}

var app = new Application();
$(document).ready(function () {
    $("#ap_list").hide();
    $("#config_dlg").hide();
    app.loadAdapterList();
    app.refreshStatus();
    $("#cur_adapter").trigger("change");
//    app.showSoftKeyboard();
    app.connectionDeviceState(function(new_state, old_state, reson){
        /*NM_DEVICE_STATE_UNKNOWN = 0
         The device is in an unknown state.
         NM_DEVICE_STATE_UNMANAGED = 10
         The device is recognized but not managed by NetworkManager.
         NM_DEVICE_STATE_UNAVAILABLE = 20
         The device cannot be used (carrier off, rfkill, etc).
         NM_DEVICE_STATE_DISCONNECTED = 30
         The device is not connected.
         NM_DEVICE_STATE_PREPARE = 40
         The device is preparing to connect.
         NM_DEVICE_STATE_CONFIG = 50
         The device is being configured.
         NM_DEVICE_STATE_NEED_AUTH = 60
         The device is awaiting secrets necessary to continue connection.
         NM_DEVICE_STATE_IP_CONFIG = 70
         The IP settings of the device are being requested and configured.
         NM_DEVICE_STATE_IP_CHECK = 80
         The device's IP connectivity ability is being determined.
         NM_DEVICE_STATE_SECONDARIES = 90
         The device is waiting for secondary connections to be activated.
         NM_DEVICE_STATE_ACTIVATED = 100
         The device is active.
         NM_DEVICE_STATE_DEACTIVATING = 110
         The device's network connection is being torn down.
         NM_DEVICE_STATE_FAILED = 120
         The device is in a failure state following an attempt to activate it.



         NM_DEVICE_STATE_REASON
         NM_DEVICE_STATE_REASON_UNKNOWN = 0
         The reason for the device state change is unknown.
         NM_DEVICE_STATE_REASON_NONE = 1
         The state change is normal.
         NM_DEVICE_STATE_REASON_NOW_MANAGED = 2
         The device is now managed.
         NM_DEVICE_STATE_REASON_NOW_UNMANAGED = 3
         The device is no longer managed.
         NM_DEVICE_STATE_REASON_CONFIG_FAILED = 4
         The device could not be readied for configuration.
         NM_DEVICE_STATE_REASON_CONFIG_UNAVAILABLE = 5
         IP configuration could not be reserved (no available address, timeout, etc).
         NM_DEVICE_STATE_REASON_CONFIG_EXPIRED = 6
         The IP configuration is no longer valid.
         NM_DEVICE_STATE_REASON_NO_SECRETS = 7
         Secrets were required, but not provided.
         NM_DEVICE_STATE_REASON_SUPPLICANT_DISCONNECT = 8
         The 802.1X supplicant disconnected from the access point or authentication server.
         NM_DEVICE_STATE_REASON_SUPPLICANT_CONFIG_FAILED = 9
         Configuration of the 802.1X supplicant failed.
         NM_DEVICE_STATE_REASON_SUPPLICANT_FAILED = 10
         The 802.1X supplicant quit or failed unexpectedly.
         NM_DEVICE_STATE_REASON_SUPPLICANT_TIMEOUT = 11
         The 802.1X supplicant took too long to authenticate.
         NM_DEVICE_STATE_REASON_PPP_START_FAILED = 12
         The PPP service failed to start within the allowed time.
         NM_DEVICE_STATE_REASON_PPP_DISCONNECT = 13
         The PPP service disconnected unexpectedly.
         NM_DEVICE_STATE_REASON_PPP_FAILED = 14
         The PPP service quit or failed unexpectedly.
         NM_DEVICE_STATE_REASON_DHCP_START_FAILED = 15
         The DHCP service failed to start within the allowed time.
         NM_DEVICE_STATE_REASON_DHCP_ERROR = 16
         The DHCP service reported an unexpected error.
         NM_DEVICE_STATE_REASON_DHCP_FAILED = 17
         The DHCP service quit or failed unexpectedly.
         NM_DEVICE_STATE_REASON_SHARED_START_FAILED = 18
         The shared connection service failed to start.
         NM_DEVICE_STATE_REASON_SHARED_FAILED = 19
         The shared connection service quit or failed unexpectedly.
         NM_DEVICE_STATE_REASON_AUTOIP_START_FAILED = 20
         The AutoIP service failed to start.
         NM_DEVICE_STATE_REASON_AUTOIP_ERROR = 21
         The AutoIP service reported an unexpected error.
         NM_DEVICE_STATE_REASON_AUTOIP_FAILED = 22
         The AutoIP service quit or failed unexpectedly.
         NM_DEVICE_STATE_REASON_MODEM_BUSY = 23
         Dialing failed because the line was busy.
         NM_DEVICE_STATE_REASON_MODEM_NO_DIAL_TONE = 24
         Dialing failed because there was no dial tone.
         NM_DEVICE_STATE_REASON_MODEM_NO_CARRIER = 25
         Dialing failed because there was carrier.
         NM_DEVICE_STATE_REASON_MODEM_DIAL_TIMEOUT = 26
         Dialing timed out.
         NM_DEVICE_STATE_REASON_MODEM_DIAL_FAILED = 27
         Dialing failed.
         NM_DEVICE_STATE_REASON_MODEM_INIT_FAILED = 28
         Modem initialization failed.
         NM_DEVICE_STATE_REASON_GSM_APN_FAILED = 29
         Failed to select the specified GSM APN.
         NM_DEVICE_STATE_REASON_GSM_REGISTRATION_NOT_SEARCHING = 30
         Not searching for networks.
         NM_DEVICE_STATE_REASON_GSM_REGISTRATION_DENIED = 31
         Network registration was denied.
         NM_DEVICE_STATE_REASON_GSM_REGISTRATION_TIMEOUT = 32
         Network registration timed out.
         NM_DEVICE_STATE_REASON_GSM_REGISTRATION_FAILED = 33
         Failed to register with the requested GSM network.
         NM_DEVICE_STATE_REASON_GSM_PIN_CHECK_FAILED = 34
         PIN check failed.
         NM_DEVICE_STATE_REASON_FIRMWARE_MISSING = 35
         Necessary firmware for the device may be missing.
         NM_DEVICE_STATE_REASON_REMOVED = 36
         The device was removed.
         NM_DEVICE_STATE_REASON_SLEEPING = 37
         NetworkManager went to sleep.
         NM_DEVICE_STATE_REASON_CONNECTION_REMOVED = 38
         The device's active connection was removed or disappeared.
         NM_DEVICE_STATE_REASON_USER_REQUESTED = 39
         A user or client requested the disconnection.
         NM_DEVICE_STATE_REASON_CARRIER = 40
         The device's carrier/link changed.
         NM_DEVICE_STATE_REASON_CONNECTION_ASSUMED = 41
         The device's existing connection was assumed.
         NM_DEVICE_STATE_REASON_SUPPLICANT_AVAILABLE = 42
         The 802.1x supplicant is now available.
         NM_DEVICE_STATE_REASON_MODEM_NOT_FOUND = 43
         The modem could not be found.
         NM_DEVICE_STATE_REASON_BT_FAILED = 44
         The Bluetooth connection timed out or failed.
         NM_DEVICE_STATE_REASON_GSM_SIM_NOT_INSERTED = 45
         GSM Modem's SIM Card not inserted.
         NM_DEVICE_STATE_REASON_GSM_SIM_PIN_REQUIRED = 46
         GSM Modem's SIM Pin required.
         NM_DEVICE_STATE_REASON_GSM_SIM_PUK_REQUIRED = 47
         GSM Modem's SIM Puk required.
         NM_DEVICE_STATE_REASON_GSM_SIM_WRONG = 48
         GSM Modem's SIM wrong
         NM_DEVICE_STATE_REASON_INFINIBAND_MODE = 49
         InfiniBand device does not support connected mode.
         NM_DEVICE_STATE_REASON_DEPENDENCY_FAILED = 50
         A dependency of the connection failed.
         NM_DEVICE_STATE_REASON_BR2684_FAILED = 51
         Problem with the RFC 2684 Ethernet over ADSL bridge.
         NM_DEVICE_STATE_REASON_MODEM_MANAGER_UNAVAILABLE = 52
         ModemManager was not running or quit unexpectedly.
         NM_DEVICE_STATE_REASON_SSID_NOT_FOUND = 53
         The 802.11 Wi-Fi network could not be found.
         NM_DEVICE_STATE_REASON_SECONDARY_CONNECTION_FAILED = 54
         A secondary connection of the base connection failed.
         */
        if(new_state==50){
            app.changeState("连接中...", null, null, null);
        }
        if(new_state==120){
            var ssid = $("#cur_ssid").val();

            app.deleteConnection(ssid);
            app.changeState("连接失败", null, null, null);
            if(reson==7){
                app.changeState("密码不正确", null, null, null);
                $("#confi_dlg_msg").html('<span style="color:red">密码不正确,请重新输入密码</span>');
                $("#config_dlg").show();
            }else{
                app.changeState("连接超时,信号太弱了...");
            }
        }
        if(new_state==100){
            app.loadAdapterList();
            app.refreshStatus();
            $("#cur_adapter").trigger("change");
        }
        console.log(String.format("{0}{1}{2}", new_state, old_state, reson));
    });
    WifiSignal.networkStateSignal.connect(function(state){
        app.loadAdapterList();
        app.refreshStatus();
        $("#cur_adapter").trigger("change");
    });

    $("#refreshAp").click(function () {
        app.loadAccessPoint();
    });
    $("#refreshAp").trigger("click");

    $("#disconnect").click(function(){
        app.disconnect();
    });
    $("#connectAp").click(function () {
        var ssid = $("#cur_ssid").val();
        var pwd = $("#cur_pwd").val();
        app.connectionAp(ssid, pwd);

        $("#config_dlg").hide();
        $("#ap_list").hide();
    });
});